<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/15
 * Time: 10:30
 */

namespace app\admin\controller;


use app\common\model\AmountLog;
use app\common\model\Config;
use app\common\model\Level;
use app\common\model\MessageTemplate;
use app\common\model\NoticeMessage;
use app\common\model\ServiceOrder;
use app\common\model\UserCommission;
use app\Request;

class Service
{
    public function serviceList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['s.status', '=', $param['status']];
        }
        if (isset($param['user_name']) && $param['user_name']) {
            $where[] = ['u.nickname|u.phone', '=', $param['user_name']];
        }
        if (isset($param['pid_tab']) && !empty($param['pid_tab'])) {
            $where[] = ['s.pid_tab', '=', $param['pid_tab']];
        }
        if (isset($param['son_tab']) && !empty($param['son_tab'])) {
            $where[] = ['s.son_tab', '=', $param['son_tab']];
        }
        if (isset($param['title']) && !empty($param['title'])) {
            $where[] = ['s.title', 'like', '%' . $param['title'] . '%'];
        }
        $serviceModel = new \app\common\model\Service();
        $list = $serviceModel
            ->alias('s')
            ->leftJoin('tab_class tc', 's.son_tab = tc.id')
            ->leftJoin('tab_class tcl', 's.pid_tab = tcl.id')
            ->leftJoin('user u', 's.uid = u.id')
            ->where($where)
            ->field('s.*,u.nickname,u.avatar ,tc.name as stabname,tcl.name as ptabname')
            ->order('s.create_time', 'desc')
            ->limit($start, $limit)->select()->toArray();
        $count = $serviceModel->alias('s')
            ->leftJoin('tab_class tc', 's.son_tab = tc.id')
            ->leftJoin('tab_class tcl', 's.pid_tab = tcl.id')
            ->leftJoin('user u', 's.uid = u.id')
            ->where($where)
            ->count();
        return success('服务列表', ['list' => $list, 'count' => $count]);
    }

    /**
     * 我下单的服务订单
     */
    public function serviceOrder(Request $request)
    {
        $param = $request->param();
        $serviceOrderModel = new ServiceOrder();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['title']) && !empty($param['title'])) {
            $where[] = ['s.title', 'like', '%' . $param['title'] . '%'];
        }
        if (isset($param['id']) && !empty($param['id'])) {
            $where[] = ['s.id', '=', $param['id']];
        }
        if (isset($param['order_sn']) && !empty($param['order_sn'])) {
            $where[] = ['so.order_sn',  'like', '%' .  $param['order_sn']. '%'];
        }
        if (isset($param['order_status']) && !empty($param['order_status'])) {
            $where[] = ['so.status', '=', $param['order_status']];
        }
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['s.status', '=', $param['status']];
        }
        if (isset($param['release_user']) && !empty($param['release_user'])) {
            $where[] = ['ru.nickname|u.phone', 'like', '%' . $param['release_user'] . '%'];
        }
        if (isset($param['join_user']) && !empty($param['join_user'])) {
            $where[] = ['ju.nickname|u.phone', 'like', '%' . $param['release_user'] . '%'];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['so.create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['so.create_time', '<=', strtotime($param['end_time'])];
        }
        $list = $serviceOrderModel->alias('so')
            ->leftJoin('service s', 'so.service_id = s.id')
            ->leftJoin('tab_class tc', 's.son_tab = tc.id')
            ->leftJoin('tab_class ptc', 's.pid_tab = ptc.id')
            ->leftJoin('user ju', 'so.uid = ju.id')
            ->leftJoin('user ru', 'so.service_uid = ru.id')
            ->field('s.*,ju.nickname as ju_nickname,
             ju.avatar as ju_avatar, ru.nickname as ru_nickname ,
              ru.avatar as ru_avatar,so.status as order_status,so.evaluate_img,so.complete_img ,
              so.remark,tc.name as son_tab_name, ptc.name as p_tab_name,so.technology_score,so.id as order_id,
              so.service_score,so.voice_score,so.evaluate,so.is_comment')
            ->order('so.create_time', 'desc')
            ->limit($start, $limit)
            ->select()->toArray();
        $count = $serviceOrderModel->alias('so')
            ->leftJoin('service s', 'so.service_id = s.id')
            ->leftJoin('tab_class tc', 's.son_tab = tc.id')
            ->leftJoin('tab_class ptc', 's.pid_tab = ptc.id')
            ->leftJoin('user ju', 'so.uid = ju.id')
            ->leftJoin('user ru', 'so.service_uid = ru.id')
            ->field('s.*,ju.nickname as ju_nickname ,ju.avatar as ju_avatar ')
            ->count();
        return success('服务订单', ['list' => $list, 'count' => $count]);
    }

    /**
     * @param 我发布服务的服务订单
     */

    public function refuseServiceOrder(Request $request)
    {
        $param = $request->param();
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $serviceOrderInfo = $serviceOrderModel->where(['id' => $param['id']])->find();
        if ($serviceOrderInfo['status'] != 1) {
            return error('订单状态有误');
        }
        $serviceOrderModel->where(['id' => $param['id']])
            ->update(['status' => 5, 'update_time' => time(),'remark' => $param['remark']]);
        $userModel = new \app\common\model\User();
        $userModel->where(['id' => $serviceOrderInfo['uid']])
            ->inc('balance', $serviceOrderInfo['price'])->update();
        /* $amountModel = new AmountLog();
         $amountData  = [
             'uid' => $serviceOrderInfo['uid'],
             'amount' => $serviceOrderInfo['price'],
             'amount_type' => 1,
             'amount_direction' => 1,
             'create_time' => time(),
             'correlation_id' => $param['id'],
             'operation_source' => 7
         ];
         $amountModel->insert($amountData);*/
        $serviceModel = new \app\common\model\Service();
        $serviceInfo = $serviceModel->where(['id' => $serviceOrderInfo['service_id']])->find();
        $noticeMessageModel = new  NoticeMessage();
        $noticeMessageModel->insert([
            // 'content' =>  $param['content'],
            'uid' => $serviceOrderInfo['uid'],
            'receive_uid' => $serviceOrderInfo['service_uid'],
            'type' => 10,
            'dazi_id' => $param['id'],
            'create_time' => time(),
            'is_read' => 0
        ]);
        $messageModel = new MessageTemplate();
        $xcxMessage[]['data'] = [
            'thing1' => ['value' => '服务订单'],
            'thing2' => ['value' => $serviceInfo['title']],
            'phrase3' => ['value' => '拒绝'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];

        $xcxMessage[0]['uid'] = $serviceOrderInfo['uid'];
        $xcxMessage[0]['title'] = 'release';

        $messageModel->sendMessage(3, $xcxMessage);
        $userModel = new \app\common\model\User();
        $userInfo = $userModel->where(['id' => $serviceInfo['uid']])->find();
        $gzhMessage[0]['data'] = [
            'thing10' => ['value' => '服务'],
            'thing28' => ['value' => $userInfo['nickname']],
            'thing9' => ['value' => $serviceInfo['title']],
            'thing2' => ['value' => '拒绝'],
        ];
        $gzhMessage[0]['uid'] = $request->userInfo['id'];
        $gzhMessage[0]['title'] = 'release';
        $messageModel->sendMessage(1, $gzhMessage);
        $messageModel-> sendAliMessage($serviceOrderInfo['uid'], 'release', ['name' =>'服务'. $serviceInfo['title'],'desc'=>'拒绝订单']);

        return success('操作成功');
    }

    /**
     * 结算
     */
    public function settlementService(Request $request)
    {
        $param = $request->param();
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $serviceOrderInfo = $serviceOrderModel->where(['id' => $param['id']])->find();
        if ($serviceOrderInfo) {
            return error('订单不存在');
        }
        if ($serviceOrderInfo['status'] != 3 || $serviceOrderInfo['status'] != 2) {
            return error('订单状态有误,请刷新页面');
        }
        $serviceOrderModel->where(['id' => $param['id']])->update(['status' => 4,'update_time' => time()]);
        $userModel = new \app\common\model\User();
        $fees = Config::getConfigValue('service_fees');
        $platformAmount = bcdiv(bcmul((string)$serviceOrderInfo['price'], (string)$fees, 2), '100', 2);
        $amount = bcsub((string)$serviceOrderInfo['price'], (string)$platformAmount, 2);
        $recharge_ratio  = Config::getConfigValue('recharge_ratio');
        $userModel->where(['id' => $serviceOrderInfo['service_uid']])
            ->inc('total_income', (float)$amount)
            ->inc('surplus_income', (float)$amount)
            ->inc('service_income', (float)$amount)
            ->inc('service_number')
            ->update();
        $amountLog = [
            'uid' =>  $serviceOrderInfo['service_uid'],
            'amount' => $amount,
            'amount_type' => 2,
            'operation_source' => 10,
            'amount_direction' => 1,
            'create_time' => time(),
            'correlation_id' => $param['id'],
            'ratio' => $fees,
            'handling_fees_amount' => bcdiv($platformAmount,$recharge_ratio,2),
            'handling_fees' => $platformAmount,
            'original_price' =>$serviceOrderInfo['price']
        ];
        $amountModel = new  AmountLog();
        $amountModel->insert($amountLog);
        $serviceModel = new \app\common\model\Service();
        $serviceModel->where(['id' => $serviceOrderInfo['service_uid']])->inc('order_number')->update();
        $serviceInfo = $serviceModel->where(['id' => $serviceOrderInfo['service_id']])->find();
        $messageModel = new MessageTemplate();
        $xcxMessage[]['data'] = [
            'thing1' => ['value' => '服务订单'],
            'thing2' => ['value' => $serviceInfo['title']],
            'phrase3' => ['value' => '结算'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];

        $xcxMessage[0]['uid'] = $serviceInfo['uid'];
        $xcxMessage[0]['title'] = 'release';
        $messageModel->sendMessage(3, $xcxMessage);
        $userModel = new \app\common\model\User();

        $userInfo = $userModel->where(['id' => $serviceInfo['uid']])->find();
        $gzhMessage[0]['data'] = [
            'thing10' => ['value' => '服务'],
            'thing28' => ['value' => $userInfo['nickname']],
            'thing9' => ['value' => $serviceInfo['title']],
            'thing2' => ['value' => '结算'],
        ];
        $gzhMessage[0]['uid'] = $serviceInfo['id'];
        $gzhMessage[0]['title'] = 'release';
        $messageModel->sendMessage(1, $gzhMessage);
        $messageModel-> sendAliMessage($serviceInfo['uid'], 'release', ['name' =>'服务'. $serviceInfo['title'],'desc'=>'已结算']);
        return success('操作完成');
    }

    public function upServiceStatus(Request $request)
    {
        $param = $request->param();
        $serviceModel = new \app\common\model\Service();
        if ($param['status'] == 3) {
            $serviceOrderModel = new \app\common\model\ServiceOrder();
            $count = $serviceOrderModel->where(['service_id' => $param['id']])
                ->where('status', 'in', [1, 2])->count();
            if ($count > 0) {
                return error('服务存在未处理的订单');
            }
        }
        $data['status'] = $param['status'];
        if (isset($param['remark']) && !empty($param['remark'])) {
            $data['remark'] = $param['remark'];
        }
        $serviceInfo = $serviceModel->where(['id' => $param['id']])->find();
        $serviceModel->where(['id' => $param['id']])->update($data);
        $userModel = new \app\common\model\User();
        $userInfo = $userModel->where(['id' => $serviceInfo['uid']])->find();
        $messageModel = new MessageTemplate();
        $xcxMessage[]['data'] = [
            'thing1' => ['value' => '服务'],
            'thing2' => ['value' => $serviceInfo['title']],
            // 'phrase3' => ['value' =>'通过'],
            'time5' => ['value' => date('Y-m-d H:i:s')],
        ];

        $gzhMessage[0]['data'] = [
            'thing10' => ['value' => '服务'],
            'thing28' => ['value' => $userInfo['nickname']],
            'thing9' => ['value' => $serviceInfo['title']],
        ];
        $gzhMessage[0]['uid'] = $serviceInfo['id'];
        $gzhMessage[0]['title'] = 'release';

        if ($param['status'] == 2) {
            $xcxMessage[0]['data']['phrase3'] = '通过';
            $gzhMessage[0]['data']['thing2'] = '通过';
        } elseif ($param['status'] == 4) {
            $xcxMessage[0]['data']['phrase3'] = '驳回';
            $gzhMessage[0]['data']['thing2'] = '通过';
        } elseif ($param['status'] = 3) {
            $xcxMessage[0]['data']['phrase3'] = '下架';
            $gzhMessage[0]['data']['thing2'] = '通过';
        }
        $xcxMessage[0]['uid'] = $serviceInfo['uid'];
        $xcxMessage[0]['title'] = 'release';
        $messageModel->sendMessage(3, $xcxMessage);
        return success('操作成功');
    }


    public function serviceTopList(Request $request){
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where =[] ;
        if ( isset($param['status']) && !empty($param['status']) ){
            $where[] = ['s.status','=',$param['status']];
        }

        if (isset($param['nickname']) && !empty($param['nickname'])){
            $where[] = ['u.nickname','like','%'.$param['nickname'].'%'];
        }
        if (isset($param['phone']) && !empty($param['phone'])){
            $where[] = ['u.phone','=',$param['phone']];
        }
        if (isset($param['uid']) && !empty($param['uid'])){
            $where[] = ['s.uid','=',$param['uid']];
        }
        if (isset($param['title']) && !empty($param['title'])) {
            $where[] = ['s.title', 'like', '%' . $param['title'] . '%'];
        }
        $serviceTopLog = new \app\common\model\ServiceTopLog();
        $list = $serviceTopLog
            ->alias('st')
            ->leftJoin('service s', 'st.service_id = s.id')
            ->leftJoin('user u', 's.uid = u.id')
            ->order('s.create_time','desc')
            ->where($where)
            ->field('s.*,u.nickname,u.avatar,st.*')
            ->limit($start,$limit)->select()->toArray();
        $count = $serviceTopLog
            ->alias('st')
            ->leftJoin('service s', 'st.service_id = s.id')
            ->leftJoin('user u', 's.uid = u.id')
            ->where($where)
            ->count();
        foreach ($list as $key => $value){
            if ($value['top_expire_time'] > 0){
                $list[$key]['effective_time'] = date('Y-m-d H:i', $value['effective_time']);
            }

        }
        return success('服务置顶记录',['list' =>$list,'count'=>$count ]);

    }
    public function refuseAllOrder(Request $request){
        $param = $request->param();
        $serviceOrderModel = new \app\common\model\ServiceOrder();
        $userModel = new \app\common\model\User();
        $serviceOrder = $serviceOrderModel->where(['service_id' => $param['id'],'status' => 1])->select();
        foreach ($serviceOrder as $serviceValue){
            $serviceOrderModel->where(['id' => $serviceValue['id']])
                ->update(['status' => 5, 'update_time' => time(),'remark' => $param['remark']]);
            $userModel->where(['id' => $serviceValue['uid']])
                ->inc('balance',$serviceValue['price'])->update();
            $amountModel = new AmountLog();
            $amountData  = [
                'uid' => $serviceValue['uid'],
                'amount' => $serviceValue['price'],
                'amount_type' => 1,
                'amount_direction' => 1,
                'create_time' => time(),
                'correlation_id' => $serviceValue['id'],
                'operation_source' => 7
            ];
            $amountModel->insert($amountData);
        }
        return success('操作成功');
    }


}



/* @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */